import java.util.PriorityQueue;


/**
 * 自我实现定时器
 */
class MyTimerTask {
    private Runnable runnable;
    private long time;
    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public void run() {
        runnable.run();
    }
    public long getTime() {
        return time;
    }
}
class MyTimer implements Comparable<MyTimerTask> {
    private Object locker = new Object();
    private PriorityQueue<MyTimerTask> taskQueue = new PriorityQueue<>();

    public MyTimer() {
        Thread t = new Thread(()->{
           try {
                while(true) {
                    synchronized(locker) {
                        if(taskQueue.size() == 0) {
                            continue;
                        }
                        MyTimerTask task = taskQueue.peek();
                        long curTime = System.currentTimeMillis();
                        if(curTime >= task.getTime()) {
                            task.run();
                            taskQueue.poll();
                        }else {
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                }
           }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
    }
    public void schedule(Runnable runnable,long delay) {
        synchronized(locker) {
            MyTimerTask task = new MyTimerTask(runnable,delay);
            taskQueue.offer(task);
        }
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time- o.getTime());
    }
}
public class Demo3 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");

            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 1000);
    }
}
